<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员仪表板 - 商品评价系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            border-radius: 10px;
            margin: 5px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255,255,255,0.2);
        }
        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            border-left: 5px solid;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .stats-card.users {
            border-left-color: #3498db;
        }
        .stats-card.products {
            border-left-color: #2ecc71;
        }
        .stats-card.reviews {
            border-left-color: #f39c12;
        }
        .stats-card.pending {
            border-left-color: #e74c3c;
        }
        .stats-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .stats-label {
            color: #6c757d;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .stats-icon {
            font-size: 3rem;
            opacity: 0.3;
            position: absolute;
            right: 20px;
            top: 20px;
        }
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        .recent-activity {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        .activity-item {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }
        .activity-item:last-child {
            border-bottom: none;
        }
        .activity-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.9rem;
        }
        .activity-icon.user {
            background: #3498db;
        }
        .activity-icon.product {
            background: #2ecc71;
        }
        .activity-icon.review {
            background: #f39c12;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .navbar-brand {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <h4><i class="fas fa-tachometer-alt me-2"></i>管理后台</h4>
                        <small class="text-muted">欢迎，<span id="adminName">管理员</span></small>
                    </div>
                    
                    <ul class="nav flex-column">
<%--                        <li class="nav-item">--%>
<%--                            <a class="nav-link active" href="/product-review/page/admin/dashboard">--%>
<%--                                <i class="fas fa-home me-2"></i>仪表板--%>
<%--                            </a>--%>
<%--                        </li>--%>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/admin/users">
                                <i class="fas fa-users me-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/admin/products">
                                <i class="fas fa-box me-2"></i>商品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/admin/reviews">
                                <i class="fas fa-comments me-2"></i>评价管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/index">
                                <i class="fas fa-arrow-left me-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="#" onclick="logout()">
                                <i class="fas fa-sign-out-alt me-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <!-- 顶部导航 -->
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">仪表板</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="refreshData()">
                                <i class="fas fa-sync-alt me-1"></i>刷新数据
                            </button>
                        </div>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-primary" onclick="exportReport()">
                                <i class="fas fa-download me-1"></i>导出报告
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="stats-card users position-relative">
                            <div class="stats-number text-primary" id="totalUsers">0</div>
                            <div class="stats-label">总用户数</div>
                            <i class="fas fa-users stats-icon"></i>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="stats-card products position-relative">
                            <div class="stats-number text-success" id="totalProducts">0</div>
                            <div class="stats-label">总商品数</div>
                            <i class="fas fa-box stats-icon"></i>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="stats-card reviews position-relative">
                            <div class="stats-number text-warning" id="totalReviews">0</div>
                            <div class="stats-label">总评价数</div>
                            <i class="fas fa-comments stats-icon"></i>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="stats-card pending position-relative">
                            <div class="stats-number text-danger" id="pendingReviews">0</div>
                            <div class="stats-label">待审核评价</div>
                            <i class="fas fa-clock stats-icon"></i>
                        </div>
                    </div>
                </div>

                <!-- 图表区域 -->
                <div class="row mb-4">
                    <div class="col-lg-8">
                        <div class="chart-container">
                            <h5 class="mb-3">用户注册趋势</h5>
                            <canvas id="userTrendChart" width="400" height="200"></canvas>
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="chart-container">
                            <h5 class="mb-3">评价分布</h5>
                            <canvas id="reviewDistributionChart" width="400" height="200"></canvas>
                        </div>
                    </div>
                </div>

                <div class="row mb-4">
                    <div class="col-lg-6">
                        <div class="chart-container">
                            <h5 class="mb-3">商品分类统计</h5>
                            <canvas id="categoryChart" width="400" height="200"></canvas>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="chart-container">
                            <h5 class="mb-3">月度评价趋势</h5>
                            <canvas id="monthlyReviewChart" width="400" height="200"></canvas>
                        </div>
                    </div>
                </div>

                <!-- 最近活动 -->
                <div class="row">
                    <div class="col-lg-6">
                        <div class="recent-activity">
                            <h5 class="mb-3">最近用户注册</h5>
                            <div id="recentUsers">
                                <!-- 最近用户列表将通过JavaScript动态加载 -->
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="recent-activity">
                            <h5 class="mb-3">最新评价</h5>
                            <div id="recentReviews">
                                <!-- 最新评价列表将通过JavaScript动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let charts = {};
        
        $(document).ready(function() {
            // 检查管理员权限
            checkAdminPermission();
            
            // 加载统计数据
            loadStatistics();
            
            // 初始化图表
            initCharts();
            
            // 加载最近活动
            loadRecentActivities();
        });
        
        // 检查管理员权限
        function checkAdminPermission() {
            $.ajax({
                url: '/product-review/user/current',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        currentUser = result.data;
                        if (result.data.role !== 'ADMIN') {
                            alert('您没有管理员权限');
                            window.location.href = '/product-review/page/index';
                            return;
                        }
                        $('#adminName').text(result.data.username);
                    } else {
                        alert('请先登录');
                        window.location.href = '/product-review/page/login';
                    }
                },
                error: function() {
                    alert('请先登录');
                    window.location.href = '/product-review/page/login';
                }
            });
        }
        
        // 加载统计数据
        function loadStatistics() {
            // 加载用户统计
            $.ajax({
                url: '/product-review/user/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200) {
                        $('#totalUsers').text(result.data ? result.data.length : 0);
                    }
                }
            });
            
            // 加载商品统计
            $.ajax({
                url: '/product-review/product/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200) {
                        $('#totalProducts').text(result.data ? result.data.length : 0);
                    }
                }
            });
            
            // 加载评价统计
            $.ajax({
                url: '/product-review/review/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200) {
                        const reviews = result.data || [];
                        $('#totalReviews').text(reviews.length);
                        
                        // 计算待审核评价
                        const pendingCount = reviews.filter(r => r.status === 'PENDING').length;
                        $('#pendingReviews').text(pendingCount);
                    }
                }
            });
        }
        
        // 初始化图表
        function initCharts() {
            // 用户注册趋势图
            const userTrendCtx = document.getElementById('userTrendChart').getContext('2d');
            charts.userTrend = new Chart(userTrendCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '新注册用户',
                        data: [],
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // 评价分布饼图
            const reviewDistCtx = document.getElementById('reviewDistributionChart').getContext('2d');
            charts.reviewDistribution = new Chart(reviewDistCtx, {
                type: 'doughnut',
                data: {
                    labels: ['5星', '4星', '3星', '2星', '1星'],
                    datasets: [{
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: [
                            '#2ecc71',
                            '#3498db',
                            '#f39c12',
                            '#e67e22',
                            '#e74c3c'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
            
            // 商品分类统计
            const categoryCtx = document.getElementById('categoryChart').getContext('2d');
            charts.category = new Chart(categoryCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: '商品数量',
                        data: [],
                        backgroundColor: '#2ecc71'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // 月度评价趋势
            const monthlyReviewCtx = document.getElementById('monthlyReviewChart').getContext('2d');
            charts.monthlyReview = new Chart(monthlyReviewCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '评价数量',
                        data: [],
                        borderColor: '#f39c12',
                        backgroundColor: 'rgba(243, 156, 18, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // 加载图表数据
            loadChartData();
        }
        
        // 加载图表数据
        function loadChartData() {
            // 加载用户注册趋势数据
            $.ajax({
                url: '/product-review/user/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        updateUserTrendChart(result.data);
                    }
                }
            });
            
            // 加载评价分布数据
            $.ajax({
                url: '/product-review/review/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        updateReviewDistributionChart(result.data);
                        updateMonthlyReviewChart(result.data);
                    }
                }
            });
            
            // 加载商品分类数据
            $.ajax({
                url: '/product-review/product/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        updateCategoryChart(result.data);
                    }
                }
            });
        }
        
        // 更新用户注册趋势图
        function updateUserTrendChart(users) {
            const last7Days = [];
            const userCounts = [];
            
            for (let i = 6; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                const dateStr = date.toISOString().split('T')[0];
                last7Days.push(date.toLocaleDateString());
                
                const count = users.filter(user => {
                    const userDate = new Date(user.createTime).toISOString().split('T')[0];
                    return userDate === dateStr;
                }).length;
                
                userCounts.push(count);
            }
            
            charts.userTrend.data.labels = last7Days;
            charts.userTrend.data.datasets[0].data = userCounts;
            charts.userTrend.update();
        }
        
        // 更新评价分布图
        function updateReviewDistributionChart(reviews) {
            const distribution = [0, 0, 0, 0, 0];
            
            reviews.forEach(review => {
                if (review.rating >= 1 && review.rating <= 5) {
                    distribution[5 - review.rating]++;
                }
            });
            
            charts.reviewDistribution.data.datasets[0].data = distribution;
            charts.reviewDistribution.update();
        }
        
        // 更新商品分类图
        function updateCategoryChart(products) {
            const categoryMap = {};
            
            products.forEach(product => {
                const category = product.category || '未分类';
                categoryMap[category] = (categoryMap[category] || 0) + 1;
            });
            
            const categories = Object.keys(categoryMap);
            const counts = Object.values(categoryMap);
            
            charts.category.data.labels = categories;
            charts.category.data.datasets[0].data = counts;
            charts.category.update();
        }
        
        // 更新月度评价趋势图
        function updateMonthlyReviewChart(reviews) {
            const last6Months = [];
            const reviewCounts = [];
            
            for (let i = 5; i >= 0; i--) {
                const date = new Date();
                date.setMonth(date.getMonth() - i);
                const monthStr = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
                last6Months.push(date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'short' }));
                
                const count = reviews.filter(review => {
                    const reviewDate = new Date(review.createTime);
                    const reviewMonthStr = reviewDate.getFullYear() + '-' + String(reviewDate.getMonth() + 1).padStart(2, '0');
                    return reviewMonthStr === monthStr;
                }).length;
                
                reviewCounts.push(count);
            }
            
            charts.monthlyReview.data.labels = last6Months;
            charts.monthlyReview.data.datasets[0].data = reviewCounts;
            charts.monthlyReview.update();
        }
        
        // 加载最近活动
        function loadRecentActivities() {
            // 加载最近注册用户
            $.ajax({
                url: '/product-review/user/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        const recentUsers = result.data
                            .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                            .slice(0, 5);
                        displayRecentUsers(recentUsers);
                    }
                }
            });
            
            // 加载最新评价
            $.ajax({
                url: '/product-review/review/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        const recentReviews = result.data
                            .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                            .slice(0, 5);
                        displayRecentReviews(recentReviews);
                    }
                }
            });
        }
        
        // 显示最近用户
        function displayRecentUsers(users) {
            let html = '';
            
            if (users.length === 0) {
                html = '<div class="text-center text-muted py-3">暂无数据</div>';
            } else {
                users.forEach(user => {
                    const createTime = new Date(user.createTime).toLocaleDateString();
                    html += `
                        <div class="activity-item d-flex align-items-center">
                            <div class="activity-icon user me-3">
                                <i class="fas fa-user"></i>
                            </div>
                            <div class="flex-grow-1">
                                <div class="fw-bold">\${user.username}</div>
                                <small class="text-muted">\${user.email ? '未设置邮箱' : user.email}</small>
                            </div>
                            <div class="text-end">
                                <small class="text-muted">\${createTime}</small>
                            </div>
                        </div>
                    `;
                });
            }
            
            $('#recentUsers').html(html);
        }
        
        // 显示最新评价
        function displayRecentReviews(reviews) {
            let html = '';
            
            if (reviews.length === 0) {
                html = '<div class="text-center text-muted py-3">暂无数据</div>';
            } else {
                reviews.forEach(review => {
                    const createTime = new Date(review.createTime).toLocaleDateString();
                    const stars = generateStars(review.rating);
                    html += `
                        <div class="activity-item d-flex align-items-center">
                            <div class="activity-icon review me-3">
                                <i class="fas fa-comment"></i>
                            </div>
                            <div class="flex-grow-1">
                                <div class="fw-bold">\${review.username ? '匿名用户' : review.username}</div>
                                <div class="text-warning">\${stars}</div>
                                <small class="text-muted">\${review.content ? '' : (review.content.length() > 30 ? review.content.substring(0, 30).concat('...') : review.content)}</small>
                            </div>
                            <div class="text-end">
                                <small class="text-muted">\${createTime}</small>
                                <div>
                                    <span class="badge \${review.status == 'APPROVED' ? 'bg-success' : 'bg-warning'}">
                                    \${review.status == 'APPROVED' ? '已审核' : '待审核'}
                                    </span>
                                </div>
                            </div>
                        </div>
                    `;
                });
            }
            
            $('#recentReviews').html(html);
        }
        
        // 生成星级显示
        function generateStars(rating) {
            let html = '';
            for (let i = 1; i <= 5; i++) {
                if (i <= rating) {
                    html += '<i class="fas fa-star"></i>';
                } else {
                    html += '<i class="far fa-star"></i>';
                }
            }
            return html;
        }
        
        // 刷新数据
        function refreshData() {
            loadStatistics();
            loadChartData();
            loadRecentActivities();
        }
        
        // 导出报告
        function exportReport() {
            alert('导出报告功能待完善');
        }
        
        // 退出登录
        function logout() {
            $.ajax({
                url: '/product-review/user/logout',
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        window.location.href = '/product-review/page/index';
                    } else {
                        alert('退出登录失败：' + result.message);
                    }
                },
                error: function() {
                    alert('退出登录失败');
                }
            });
        }
    </script>
</body>
</html>